package com.hoperun.utils;

/**
 * Copyright: Copyright (c) 2014 CNPCMALL <br/>
 * ClassName: FileController.java
 * 
 * @Description: 该类的功能描述
 * 
 * @version: v1.0.0
 * @author: fuyu
 * @date: 2014-8-6 下午2:01:04
 * 
 *        Modification History: Date Author Version Description
 *        ---------------------------------------------------------* 2014-8-6
 *        fuyu v1.0.0 修改原因
 */
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.shiro.crypto.hash.Sha256Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.hoperun.framework.io.CommonFile;

public class XHZUtils {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(XHZUtils.class);

	private static ResourceLoader resourceLoader = new DefaultResourceLoader();

	public static String uploadAndGetUrl(File file, String owner,
			String basePath, String createTime, String fileName)
			throws IOException {
		CommonFile cf = new CommonFile(file);
		String relativePath = generatePath(file, owner, createTime, fileName);
		Resource resource = resourceLoader.getResource(StringUtils
				.cleanPath(basePath + relativePath));
		cf.save(resource.getFile());
		cf.close();
		return "/file" + relativePath.replace('\\', '/');
	}

	public static String uploadAndGetUrl(MultipartFile file, String owner,
			String basePath, String createTime, String fileName)
			throws IOException {
		CommonFile cf = new CommonFile(file.getInputStream());
		String relativePath = generatePath(file, owner, createTime, fileName);
		Resource resource = resourceLoader.getResource(StringUtils
				.cleanPath(basePath + File.separator + relativePath));
		cf.save(resource.getFile());
		cf.close();
		// url for web
		return "/file" + relativePath.replace('\\', '/');
	}

	public static Resource uploadResourcePath(MultipartFile file, String owner,
			String basePath, String createTime, String fileName)
			throws IOException {
		String relativePath = generatePath(file, owner, createTime, fileName);
		Resource resource = resourceLoader.getResource(StringUtils
				.cleanPath(basePath + File.separator + relativePath));
		// url for web
		return resource;
	}

	public static boolean isAllowedFileSuffix(MultipartFile file,
			Set<String> suffixs) {
		boolean passed = false;
		String contenttype = file.getContentType();
		String fileName = file.getOriginalFilename();

		if (org.apache.commons.lang.StringUtils.isNotBlank(fileName)) {
			String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
			if (suffixs.contains(fileSuffix)) {
				passed = true;
			}
		}
		LOGGER.debug("suffixs is  {}", suffixs);
		LOGGER.debug("contenttype is  {}", contenttype);
		LOGGER.debug("fileName is  {}", fileName);
		return passed;
	}

	public static String generatePath(MultipartFile file, String owner,
			String createTime, String fileName) {
		if (owner == null) {
			return generateDataFolder(createTime) + File.separator + fileName;
		} else {
			return StringUtils.cleanPath(generatePathByOwner(file, owner,
					createTime, fileName));
		}
	}

	public static String generateDataFolder(String createTime) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String dataFolder = File.separator + df.format(new Date());
		if (createTime != null && !"".equals(createTime)) {
			dataFolder = createTime;
		}
		return dataFolder;
	}

	public static String generatePathByOwner(MultipartFile file, String owner,
			String createTime, String fileName) {

		return StringUtils.cleanPath(File.separator + owner
				+ generateDataFolder(createTime) + File.separator + fileName);
	}

	public static boolean removeFile(String relativePath, String basePath)
			throws IOException {
		Resource resource = resourceLoader.getResource(StringUtils
				.cleanPath(basePath + File.separator + relativePath));
		File file = resource.getFile();
		if (file.exists()) {
			file.delete();
			return true;
		}
		return false;
	}

	public static String generatePassword(String password) {
		return new Sha256Hash(password, null, 1024).toBase64();
	}

	/**
	 * @param ids
	 * @return String 遍历set集合,生成一个一个5,6类似的字符串
	 */
	public static String set2String(Set<?> ids) {
		if (ids.size() != 0) {
			StringBuffer sb = new StringBuffer();
			for (Object string : ids) {
				sb.append(new StringBuffer(String.valueOf(string)));
				sb.append(",");
			}
			String str = sb.toString();
			str = str.substring(0, str.length() - 1);
			return str.toString();
		}
		return "";
	}

	/**
	 * @param ids
	 * @return String 遍历set集合,生成一个一个5,6类似的字符串
	 */
	public static String array2String(Long[] ids) {
		if (ids.length != 0) {
			StringBuffer sb = new StringBuffer();
			for (Long string : ids) {
				sb.append(new StringBuffer(string.toString()));
				sb.append(",");
			}
			String str = sb.toString();
			str = str.substring(0, str.length() - 1);
			return str.toString();
		}
		return "";
	}

	/**
	 * @param List
	 *            ids
	 * @return String 遍历list集合,生成一个一个5,6类似的字符串
	 */
	public static String list2String(List<String> Ids) {
		if (Ids.size() != 0) {
			StringBuffer sb = new StringBuffer();
			for (String string : Ids) {
				sb.append(new StringBuffer("'"+string+"'"));
				sb.append(",");
			}
			String str = sb.toString();
			str = str.substring(0, str.length() - 1);
			return str;
		}
		return "";
	}

	/**
	 * @param List
	 *            ids
	 * @return String 遍历list集合,生成一个一个5,6类似的字符串
	 */
	public static String longList2String(List<Long> Ids) {
		if (Ids.size() != 0) {
			StringBuffer sb = new StringBuffer();
			for (Long string : Ids) {
				sb.append(new StringBuffer(Long.toString(string)));
				sb.append(",");
			}
			String str = sb.toString();
			str = str.substring(0, str.length() - 1);
			return str;
		}
		return "";
	}

	private static boolean isMatch(String regex, String orginal) {
		if (orginal == null || orginal.trim().equals("")) {
			return false;
		}
		Pattern pattern = Pattern.compile(regex);
		Matcher isNum = pattern.matcher(orginal);
		return isNum.matches();
	}

	public static boolean isPositiveInteger(String orginal) {
		return isMatch("^\\+{0,1}[1-9]\\d*", orginal);
	}

	public static boolean isNegativeInteger(String orginal) {
		return isMatch("^-[1-9]\\d*", orginal);
	}

	public static boolean isWholeNumber(String orginal) {
		return isMatch("[+-]{0,1}0", orginal) || isPositiveInteger(orginal)
				|| isNegativeInteger(orginal);
	}

	public static boolean isPositiveDecimal(String orginal) {
		return isMatch("\\+{0,1}[0]\\.[1-9]*|\\+{0,1}[1-9]\\d*\\.\\d*", orginal);
	}

	public static boolean isNegativeDecimal(String orginal) {
		return isMatch("^-[0]\\.[1-9]*|^-[1-9]\\d*\\.\\d*", orginal);
	}

	public static boolean isDecimal(String orginal) {
		return isMatch("[-+]{0,1}\\d+\\.\\d*|[-+]{0,1}\\d*\\.\\d+", orginal);
	}

	public static boolean isRealNumber(String orginal) {
		return isWholeNumber(orginal) || isDecimal(orginal);
	}

	public static String UUID() {
		String uuid = java.util.UUID.randomUUID().toString();
		return uuid.replace("-", "");
	}

	public static String generatePath(File file, String owner,
			String createTime, String fileName) {
		if (owner == null) {
			return generateDataFolder(createTime) + File.separator + fileName;
		} else {
			return StringUtils.cleanPath(generatePathByOwner(file, owner,
					createTime, fileName));
		}
	}

	public static String generatePathByOwner(File file, String owner,
			String createTime, String fileName) {

		return StringUtils.cleanPath(File.separator + owner
				+ generateDataFolder(createTime) + File.separator + fileName);
	}
	
	private static final String CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	public static String getRandomStr(int length)
	{
		StringBuffer sb = new StringBuffer(); 
		Random random = new Random(); 
		for (int i = 0; i < length; i++) {
			sb.append(CHARS.charAt(random.nextInt(CHARS.length()))); 
		} 
		return sb.toString(); 
	}

	public static void main(String[] args) {
		// System.out.println(StringUtils.replaceEach("/WEB-INF\\a", new
		// String[]{"/","\\"}, new String[]{File.separator,File.separator}));
		// FileSystemResourceLoader fileSystemResourceLoader = new
		// FileSystemResourceLoader();
		// Path
		// ResourceLoader resourceLoader = new DefaultResourceLoader();
		// Resource resource =
		// resourceLoader.getResource("file:///opt/aaa/bbb");
		// System.out.println(resource.exists());

		System.out.println(isRealNumber("12.1"));

		System.out.println(isRealNumber("12.0"));

		System.out.println(isRealNumber("ss12"));
	}

	// 通过request获取客户端IP
	public static String getRemoteHost(
			javax.servlet.http.HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
	}
}
